﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Telerik.WinControls;
using Telerik.WinControls.UI;
using FukiERP.Common.Constants;
using FukiERP.Common.DTO;
using FukiERP.Helper;
using FukiERP.Services.DBContext;
using FukiERP.Services.Helper;

namespace FukiERP.Selling
{
    public partial class SellingForm : Telerik.WinControls.UI.RadForm
    {
        int _currentCustomerID = 0;
        int _totalNumber = 0;
        int _totalvalue = 0;
        Services.DBContext.Product _currentProduct = null;
        public SellingForm()
        {
            InitializeComponent();
        }

        private void SellingForm_Load(object sender, EventArgs e) {
            _drpGender.SelectedIndex = 0;
            _drpPaymentMethod.SelectedIndex = 0;
            _drpSellingMethod.SelectedIndex = 0;
        }

        private void _tbxCusPhone_Leave(object sender, EventArgs e) {
            FukiERPDataContext context = DataAccess.GetDBContext();
            Customer customer = context.Customers.Where(c => c.Phone == _tbxCusPhone.Text).FirstOrDefault();
            if (customer != null) {
                _currentCustomerID = customer.Id;
                _tbxCusName.Text = customer.Name;
                _tbxCusDevice.Text = customer.DeviceModel;
                _tbxCusEmail.Text = customer.Email;
                _tbxCusCarrier.Text = customer.Carrier;
                _tbxCusAddress.Text = customer.Address;
                _drpGender.SelectedValue = customer.Gender;
                _drpGender.Text = customer.Gender;
            }
        }

        private void _tbxProCode_Leave(object sender, EventArgs e) {
            FukiERPDataContext context = DataAccess.GetDBContext();
            Services.DBContext.Product product = context.Products.Where(c => c.Code == _tbxProCode.Text).FirstOrDefault();
            if (product != null) {
                 //checking inventory
                Inventory inven = context.Inventories.Where(c => c.ProductID == product.ID).FirstOrDefault();
                if (inven == null || inven.Quantity <= 0) {
                    MessageBox.Show(MessageConstants.InventoryIsMessage);
                    return;
                }
                _tbxSellPrice.Text = product.SalePrice.ToString();
                _tbxProName.Text = product.Name;
                _btnAddProduct.Enabled = true;
                _tbxQuantity.Enabled = true;
                _tbxQuantity.Text = CommonConstants.DefaultQuantity;
                _currentProduct = product;
            } else {
                ClearProductInfo();
            }
        }

        private void BtnAddProduct_Click(object sender, EventArgs e) {
            bool isvalid = ValidateValue.ValidateNumberGrateThanZero(errorProvider1, _tbxQuantity);
            if (!isvalid) {
                MessageBox.Show(MessageConstants.InvalidProductNunberMessage);
                return;
            }
            // Check Selling Info List
            List<ProductSellingInfo> sellingInfoList = null;
            if (_grdSellingInfo.DataSource == null) {
                sellingInfoList = new List<ProductSellingInfo>();
            } else {
                sellingInfoList = (List<ProductSellingInfo>)_grdSellingInfo.DataSource;
                _grdSellingInfo.DataSource = null;
            }

            ProductSellingInfo oldSI = sellingInfoList.Where(c => c.ProductID == _currentProduct.ID).FirstOrDefault();
            int quantity = Common.Helper.CommonHelper.GetNumber(_tbxQuantity.Text);
            if (oldSI != null) {
                oldSI.ProductQuantity = oldSI.ProductQuantity + quantity;
                _totalNumber += quantity;
                _totalvalue += (int)_currentProduct.SalePrice * quantity;
            } else {
                ProductSellingInfo sellingInfo = new ProductSellingInfo();
                sellingInfo.ProductID = _currentProduct.ID;
                sellingInfo.ProductCode = _currentProduct.Code;
                sellingInfo.ProductName = _currentProduct.Name;
                sellingInfo.SalePrice = (int)_currentProduct.SalePrice;
                sellingInfo.ProductQuantity = quantity;
                sellingInfoList.Add(sellingInfo);
                _totalNumber += quantity;
                _totalvalue += sellingInfo.Total;
            }
            _lblTotalQuantity.Text = _totalNumber.ToString(CommonConstants.NumberFormatParten);
            _lblTotalValue.Text = _totalvalue.ToString(CommonConstants.NumberFormatParten);
            _grdSellingInfo.DataSource = sellingInfoList;
        }

        private void _btnPurchase_Click(object sender, EventArgs e) {
            errorProvider1.Clear();
            List<ProductSellingInfo> sellingInfoList = (List<ProductSellingInfo>)_grdSellingInfo.DataSource;
            if (sellingInfoList == null || sellingInfoList.Count() == 0) {
                MessageBox.Show(MessageConstants.NoProductChosenMessage);
                return;
            }
            bool isValid = ValidateValue.ValidateRequirementGroup(errorProvider1,
                _tbxCusName, _tbxCusPhone, _tbxSaler);
            isValid = isValid || ValidateValue.ValidateDropdownGroup(errorProvider1, _drpGender,
                _drpPaymentMethod, _drpSellingMethod);

            if (isValid && PresentHelper.ShowConfirmBox(MessageConstants.CreateSellingOrderMessage)) {
                FukiERPDataContext context = DataAccess.GetDBContext();
                // Add Or update customer Information
                Customer customer = null;
                if (_currentCustomerID != 0) {
                    customer = context.Customers.Where(c => c.Id == _currentCustomerID).FirstOrDefault();
                }
                if (customer == null) {
                    customer = new Customer();
                    context.Customers.InsertOnSubmit(customer); 
                }
                
                customer.Name = _tbxCusName.Text;
                customer.Phone = _tbxCusPhone.Text;
                customer.Address = _tbxCusAddress.Text;
                customer.Carrier = _tbxCusCarrier.Text;
                customer.Email = _tbxCusEmail.Text;
                customer.Gender = _drpGender.SelectedItem.Text;
                customer.DeviceModel = _tbxCusDevice.Text;
                context.SubmitChanges();
                _currentCustomerID = customer.Id;

                // Add new Selling Order
                SellingOrder sellingOrder = new SellingOrder();
                context.SellingOrders.InsertOnSubmit(sellingOrder);
                sellingOrder.Date = DateTime.Now;
                sellingOrder.CustomerID = _currentCustomerID;
                sellingOrder.Note = _tbxSellingNote.Text;
                sellingOrder.Saler = _tbxSaler.Text;
                sellingOrder.DeliveryCost = Common.Helper.CommonHelper.GetNumber(_tbxDeliveryCost.Text);
                sellingOrder.SellingCode = Guid.NewGuid().ToString();
                sellingOrder.PaymentMethod = _drpPaymentMethod.SelectedItem.Text;
                sellingOrder.DeliveryMethod = _drpSellingMethod.SelectedItem.Text;
                context.SubmitChanges();

                // Add Selling Info
                foreach (ProductSellingInfo sp in sellingInfoList) {
                    SellingInfo si = new SellingInfo();
                    si.ProductID = sp.ProductID;
                    si.Quantity = sp.ProductQuantity;
                    si.SellPrice = sp.SalePrice;
                    si.SellingOrderID = sellingOrder.ID;
                    si.CostPrice = sp.Cost;
                    //update inventory
                    UpdateInventory(context, si.ProductID);
                    context.SellingInfos.InsertOnSubmit(si);
                }
                context.SubmitChanges();
                ClearCustomerInfo();
                ClearProductInfo();
                ClearOrderInfo();
            }
        }

        private void UpdateInventory(FukiERPDataContext context, int productID) {
            Inventory inven = context.Inventories.Where(c => c.ProductID == productID).FirstOrDefault();
            inven.Quantity -= 1;
        }

        private void _btnCreateNewOrder_Click(object sender, EventArgs e) {
            ClearCustomerInfo();
            ClearProductInfo();
            ClearOrderInfo();
        }

        private void ClearOrderInfo() {
            _currentCustomerID = 0;
            _currentProduct = null;
            _totalNumber = 0;
            _totalvalue = 0;
            PresentHelper.ClearTextBox(_tbxSellingNote, _tbxSaler, _tbxDeliveryCost, _tbxProCode);
            PresentHelper.ClearDropBox(_drpGender, _drpPaymentMethod, _drpSellingMethod);
            _grdSellingInfo.DataSource = null;
            _lblTotalValue.Text = CommonConstants.DefaultNumber;
            _lblTotalQuantity.Text = CommonConstants.DefaultNumber;
        }

        private void ClearProductInfo() {
            _btnAddProduct.Enabled = false;
            _tbxQuantity.Enabled = false;
            _tbxQuantity.Text = string.Empty;
            PresentHelper.ClearTextBox(_tbxProName, _tbxQuantity, _tbxSellPrice);
            _currentProduct = null;
            _lblTotalQuantity.Text = _totalNumber.ToString(CommonConstants.NumberFormatParten);
            _lblTotalValue.Text = _totalvalue.ToString(CommonConstants.NumberFormatParten);
        }

        private void ClearCustomerInfo() {
            _currentCustomerID = 0;
            PresentHelper.ClearTextBox(_tbxCusAddress, _tbxCusCarrier,
                _tbxCusDevice, _tbxCusEmail, _tbxCusName, _tbxCusPhone);
            PresentHelper.ClearTextBox(_drpGender);
        }
    }
}
